package com.mimc.controller.admin;

import com.jfinal.aop.Inject;
import com.jfinal.core.paragetter.Para;
import com.jfinal.plugin.activerecord.Page;
import com.mimc.core.model.SysConfig;
import com.mimc.core.service.SysConfigService;
import com.mimc.framework.domain.AjaxResult;
import com.mimc.framework.jwt.AdminTokenUtils;
import com.mimc.framework.manager.MinioManager;
import com.mimc.service.ShSysConfigService;
import io.jboot.db.model.Columns;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;

import java.util.Date;

@RequestMapping("/admin/sys/config")
public class SysConfigController extends JbootController {
    @Inject
    private SysConfigService sysConfigService;
    @Inject
    private ShSysConfigService shSysConfigService;

    public AjaxResult lists(){
        Integer page=getInt("page",1);
        Integer pageSize=getInt("pageSize",15);
        Page<SysConfig> list=sysConfigService.paginate(page,pageSize);
        return AjaxResult.success("成功",list);
    }

    public AjaxResult add(@Para("") SysConfig sysConfig){
        sysConfig.setCreateBy(AdminTokenUtils.getCurrentUser().getUsername());
        sysConfig.setCreateTime(new Date());
        if(!shSysConfigService.checkConfigKeyUnique(sysConfig)){
            return AjaxResult.error("键值不唯一");
        }
        shSysConfigService.insertConfig(sysConfig);
        return AjaxResult.success("添加成功");
    }

    public AjaxResult update(@Para("") SysConfig sysConfig){
        sysConfig.setUpdateBy(AdminTokenUtils.getCurrentUser().getUsername());
        sysConfig.setUpdateTime(new Date());
        shSysConfigService.updateConfig(sysConfig);
        if(sysConfig.getConfigKey().equals("upload.settings")){
            MinioManager.me().init();
        }
        return AjaxResult.success("更新成功");
    }

    public AjaxResult delete(Integer configId){
        SysConfig sysConfig=sysConfigService.findById(configId);
        shSysConfigService.deleteConfig(sysConfig);
        return AjaxResult.success("删除成功");
    }

    public AjaxResult reset(){
        shSysConfigService.resetConfigCache();
        return AjaxResult.success("重置成功");
    }
    //获取上传配置
    public AjaxResult upload(){
        SysConfig sysConfig=sysConfigService.findFirstByColumns(Columns.create("config_key","upload.settings"));
        return AjaxResult.success("成功",sysConfig);
    }

}
